import 'package:flutter/foundation.dart';
import 'package:xws/helpers/safe_change_notifier.dart';
import 'package:xws/models/loc_obj.dart';
import 'package:xws/models/user/user_basic_info.dart';
import 'package:xws/state/app_state.dart';
import 'package:xws/utils/dio_utils/request/user_req.dart';

class _UState {
  _UState._();
  static final UserState _userState = UserState();
}

UserState get us => _UState._userState;

/// 用户状态管理
class UserState extends ChangeNotifier with SafeChangeNotifier {
  UserState() {
    info = UserBasicInfo.fromJson(<String, dynamic>{});
  }

  /// 我的基本信息
  late UserBasicInfo info;

  /// 刷新基本信息
  Future<UserBasicInfo?> updateBasicInfo() async {
    final String city = info.city;

    /// 我的基础信息
    final UserBasicInfo? u = await userBasicInfo();

    if (u != null) {
      info = u;
      if (info.city.isEmpty) info.city = city;
      notifyListeners();
      apps.setUnread(u.unreadMessageCount);
      return u;
    }

    return null;
  }

  /// 显示到左上角的位置
  String get reg => info.region.isEmpty ? info.city : info.region;

  /// 更新位置信息
  void updateLocation(LocObj? loc) {
    if (loc != null) {
      if (loc.city != null) info.city = loc.city!;
      if (loc.district != null) info.region = loc.district!;
      notifyListeners();
    }
  }

  /// 仅更新城市信息
  void updateCity(String? city) {
    if (info.city.isEmpty && city != null && city.isNotEmpty) {
      info.city = city;
      notifyListeners();
    }
  }

  /// 发布一个物品
  void addApub() {
    info.publishCount++;
    notifyListeners();
  }

  /// 删除一个已发布物品
  void delApub() {
    info.publishCount--;
    notifyListeners();
  }

  /// 添加一个收藏
  void addACollect() {
    info.favoriteCount++;
    notifyListeners();
  }

  /// 移除一个收藏
  void delACollect() {
    info.favoriteCount--;
    notifyListeners();
  }

  /// 清理数据
  void clear() {
    info = UserBasicInfo.fromJson(<String, dynamic>{});
    notifyListeners();
  }
}
